package com.laot.search.controller;

import cn.hutool.core.io.FileUtil;
import com.laot.search.manager.CosManager;
import com.laot.search.service.UserService;
import com.laot.search.utils.OssUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.laot.seacher_master.model.common.BaseResponse;
import org.laot.seacher_master.model.common.ErrorCode;
import org.laot.seacher_master.model.common.ResultUtils;
import org.laot.seacher_master.model.constant.FileConstant;
import org.laot.seacher_master.model.dto.file.UploadFileRequest;
import org.laot.seacher_master.model.entity.User;
import org.laot.seacher_master.model.enums.FileUploadBizEnum;
import org.laot.seacher_master.model.exception.BusinessException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;

/**
 * 文件接口
 *
 * @author laoT
 * 
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;
    @Resource
    private CosManager cosManager;
    @Resource
    private OssUtils ossUtils;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
       if(multipartFile == null){
           throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"上传的文件不能为空！");
       }
        String url = ossUtils.uploadUtil(multipartFile);
       return ResultUtils.success(url);
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
